package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Override
    public void add(String telephone) {
        log.debug("MemberServiceImpl: add: telephone ===> " + telephone);
        Member member = memberDao.findByTelephone(telephone);
        log.debug("MemberServiceImpl: add: member ===> " + member);
        if (member==null){
            Member member1 = new Member();
            member1.setPhoneNumber(telephone);
            member1.setRegTime(new Date());
            memberDao.add(member1);
        }
    }

    @Override
    public Map<String, Object> getMemberReport() {
        List<String> months = getMonthOfYear();
        List<Long> memberCount = new ArrayList<Long>();
        log.debug("MemberServiceImpl: getMemberReport: months ===> " + months);
        for (String month : months) {
            String firstDay = month + "-01";
            String lastDay = getLastDay(firstDay);
            Long count = memberDao.findCountByLastDay(lastDay);
            memberCount.add(count);
        }
        log.debug("MemberServiceImpl: getMemberReport: memberCount ===> " + memberCount);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("months",months);
        map.put("memberCount",memberCount);
        return map;
    }

    private String getLastDay(String firstDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date firstDayDate = sdf.parse(firstDay);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(firstDayDate);
            calendar.add(Calendar.MONTH,1);
            calendar.add(Calendar.DAY_OF_MONTH,-1);
            String lastDay = sdf.format(calendar.getTime());
            return lastDay;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<String> getMonthOfYear() {
        List<String> months = new ArrayList<String>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,-12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            String str = dateFormat.format(calendar.getTime());
            months.add(str);
        }
        return months;
    }
}
